package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 新增报警规则
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警",
                                            alertRuleVo.getFunctionName(),
                                            alertRuleVo.getOperator(),
                                            alertRuleVo.getValue(),
                                            alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if(between>60){
            return;
        }

        //物模型规则，获取报警规则,iotid为"-1"时表示全部
        List<AlertRule> allAlertRules = alertRuleMapper.selectByFunctionId(
                deviceDataVo.getFunctionId(),
                "-1",
                deviceDataVo.getProductKey());


        //设备规则
        List<AlertRule> theAllAlertRules = alertRuleMapper.selectByFunctionId(
                deviceDataVo.getFunctionId(),
                deviceDataVo.getIotId(),
                deviceDataVo.getProductKey());

        Collection<AlertRule> alertRules = CollUtil.addAll(allAlertRules, theAllAlertRules);
        //无规则
        if(CollUtil.isEmpty(alertRules)){
            return;
        }

        //处理每一条数据
        alertRules.forEach(rule ->deviceDateAlarmHandler(deviceDataVo,rule));

    }

    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule rule) {
        String alertEffectivePeriod = rule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        String startTime = split[0];
        String endTime = split[1];

        LocalTime mid = deviceDataVo.getAlarmTime().toLocalTime();
        if((mid.isBefore(LocalTime.parse(startTime))) || (mid.isAfter(LocalTime.parse(endTime)))){
            log.info("不在监测时间内，没上班呢，不报警");
            return;
        }

        //阈值判断
        int compare = NumberUtil.compare(Double.valueOf(deviceDataVo.getDataValue()), rule.getValue());
        String iotId = deviceDataVo.getIotId();
        String alertCountChacheKey="alertCount:"+iotId+":"+deviceDataVo.getFunctionId()+":"+rule.getId();

        if ((rule.getOperator().equals(">=") &&compare>=0 )||
                (rule.getOperator().equals("<") &&compare<0)
        ){
            log.info("需要报警，阈值：{}  现值：{}",rule.getValue(),deviceDataVo.getDataValue());
        }else {
            log.info("数据正常，阈值：{}  现值：{}",rule.getValue(),deviceDataVo.getDataValue());
            redisTemplate.delete(alertCountChacheKey);
            return;
        }

        //看有误沉默数据
        String silenceCacheKey= "silence:"+iotId+":"+deviceDataVo.getFunctionId()+":"+rule.getId();
        String silenceCacheData = redisTemplate.opsForValue().get(silenceCacheKey);
        if (StringUtils.isNotEmpty(silenceCacheData)){
            //如果沉默数据是空的，说明可以报警，如果有值，等着沉默时间结束
            log.info("当前设备：{}  功能：{}  规则：{}  在沉默时间内，不会报警",iotId,deviceDataVo.getFunctionId(),rule.getId());
//            return;
            log.info("我先不沉默哈哈");
        }
        log.info("当前设备：{}  功能：{}  规则：{}  不在沉默时间内，会报警",iotId,deviceDataVo.getFunctionId(),rule.getId());

        //redis存报警次数
        String alertCountStr=redisTemplate.opsForValue().get(alertCountChacheKey);
        int alertCount=StringUtils.isEmpty(alertCountStr)?1:Integer.parseInt(alertCountStr)+1;

        if (alertCount!=rule.getDuration()){
            log.info("报警次数：{}  报警周期：{}  当前次数：{}  还未到报警周期，不报警",rule.getDuration(),rule.getAlertSilentPeriod(),alertCount);
            redisTemplate.opsForValue().set(alertCountChacheKey,alertCount+"");
            return;
        }

        redisTemplate.delete(alertCountChacheKey);
        redisTemplate.opsForValue().set(silenceCacheKey, deviceDataVo.getDataValue(),
                rule.getAlertSilentPeriod(),
                TimeUnit.MINUTES);

        List<Long> manList=new ArrayList<>();
        if(rule.getAlertDataType().equals(0)){//老人异常
            if(deviceDataVo.getLocationType()==0){
                manList=deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if(deviceDataVo.getLocationType()==1&& deviceDataVo.getPhysicalLocationType() == 2){
                manList=deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }
        else{
            manList=userRoleMapper.selectUserIdByRoleName("维修工");
        }


        List<Long> adminuserIds =userRoleMapper.selectUserIdByRoleName("超级管理员");

        //目前有2个员工id的集合，可能出现重复
        List<Long> allUserIds = CollUtil.addAllIfNotContains(adminuserIds, manList);

        allUserIds = CollUtil.distinct(allUserIds);

        log.info("最后被通知的人id：{}",allUserIds);

        List<AlertData> list = readyToSendAlertData(rule, deviceDataVo, allUserIds);
        //发送websocket消息
        websocketNotify(rule, list.get(0), allUserIds);
    }

    private List<AlertData> readyToSendAlertData(AlertRule alertAllRule, DeviceDataVo deviceDataVo, List<Long> allUserIds) {

        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertAllRule.getId());

        String reason = alertAllRule.getAlertRuleName()+":"+alertAllRule.getFunctionName()+":"+alertAllRule.getOperator()+alertAllRule.getValue()+" 需要报警！！！";
        alertData.setAlertReason(reason);
        alertData.setStatus(0);
        alertData.setType(alertAllRule.getAlertDataType());

        List<AlertData> alertDataList = allUserIds.stream().map(userId -> {
            //拷贝alertData
            AlertData bean = BeanUtil.toBean(alertData, AlertData.class);
            bean.setUserId(userId);
            return bean;
        }).collect(Collectors.toList());

        alertDataMapper.batchInsert(alertDataList);

        return alertDataList;

    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 发送websocket通知
     *
     * @param alertRule 报警规则
     * @param alertData 报警数据
     */
    private void websocketNotify(AlertRule alertRule, AlertData alertData, List<Long> userIds) {
        // websocket通知：弹窗消息
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(alertRule.getFunctionName());
        alertNotifyDto.setAlertDataType(alertData.getType());
        alertNotifyDto.setNotifyType(1);
        alertNotifyDto.setVoiceNotifyStatus(1);
        //给指定消费者发送消息
        webSocketServer.sendMessageToConsumer(alertNotifyDto, userIds);
    }
}
